<template>
  <!-- 报告单元 -->
  <div id="smartScreenPreview">
    <Breadcrumb content="智能屏" />
    <div class="bodyContent">
      <el-tabs type="border-card">
        <el-tab-pane label="基础字典">
          <Splitpanes class="area">
            <Pane size="50">
              <vxe-toolbar perfect>
                <template #buttons>
                  <vxe-input v-model="smartScreenForm.searchValue" type="search" clearable class="vxeInputSearch"
                    placeholder="关键字查询" @keyup="keyupEnter" @clear="getSmartScreenList"></vxe-input>
                  <vxe-button type="text" class="button-blue" icon="vxe-icon-refresh" content="刷新" :loading="showLoading"
                    @click="getSmartScreenList"></vxe-button>
                  <vxe-button type="text" icon="vxe-icon-delete" class="button-red" content="删除"
                    @click="handleDelete"></vxe-button>
                  <!-- <vxe-button type="text" class="button-blue" icon="vxe-icon-sort" content="数据同步" :loading="showLoading1" @click="pullPloyee"></vxe-button> -->
                </template>
              </vxe-toolbar>

              <div class="leftTable">
                <vxe-table ref="smartScreenTable" border="inner" align="left" class="mytable-scrollbar" :loading="showLoading"
                  height="auto" :data="smartScreenList" :expand-config="{ expandAll: true, reserve: true }"
                  @current-change="userRowClick" :row-config="{ isCurrent: true, isHover: true }" :keyboard-config="{
                    isArrow: true,
                    isTab: true,
                    isEdit: false
                  }" :edit-config="{ trigger: 'dblclick', mode: 'row', showStatus: true }" resizable show-overflow
                  keep-source>
                  <vxe-column type="checkbox" width="30"></vxe-column>
                  <vxe-column type="seq" title="#" width="30"></vxe-column>
                  <vxe-column field="smartCode" title="智能屏编号" width="90"></vxe-column>
                  <vxe-column field="smartName" title="智能屏名称"></vxe-column>
                  <!-- <vxe-column field="status" title="智能屏状态"></vxe-column> -->
                  <vxe-column field="smartAddress" title="智能屏位置"></vxe-column>
                  <vxe-column field="smartType" title="智能屏类型"></vxe-column>
                  <vxe-column field="status" title="状态" width="80" align="center">
                    <template #default="{ row }">
                      <span class="table-tag" :class="`bg-${stateList[Number(row.status) - 1].color}`">{{
                        getIsStaticStatusDesc(row) }}</span>
                    </template>
                  </vxe-column>
                  <!-- <vxe-column field="isEnabled" title="是否启用" width="80" align="center" checked-value="0"
                    unchecked-value="1">
                    <template #default="{ row }">
                      <el-tag :type="getIsStaticTagType(row)">
                        {{ getIsStaticStatusDesc(row) }}
                      </el-tag>
                    </template>
                  </vxe-column> -->
                </vxe-table>
              </div>
            </Pane>

            <!-- <Pane size="50">
              <el-tabs type="border-card">
                <el-tab-pane label="预览信息">
                  <TestReport v-if="showTestReport" ref="testReportRef" />
                  <SSReport v-else ref="ssReportRef" />
                </el-tab-pane>
              </el-tabs>
            </Pane> -->
            <Pane size="50">
              <el-tabs type="border-card">
                <el-tab-pane label="预览信息">
                  <!-- <component :is="currentReportComponent" :ref="currentReportRef"
                    :smartCode="smartScreenForm.smartCode" /> -->
                    <TestReport/>
                </el-tab-pane>
              </el-tabs>
            </Pane>
          </Splitpanes>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<script setup lang="ts">
// 引入组件区 ==========
import Breadcrumb from '@/components/Breadcrumb.vue';
import { ref, reactive, getCurrentInstance, onMounted, computed } from 'vue';
import { IsEmpty, pageSizes } from '../../../utils/common'; //导入工具函数
import { Splitpanes, Pane } from 'splitpanes';
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage'; //提示信息
import { funBdsJsResult } from '@/utils/Expression'; //函数公式
import { AppStore } from '@/stores/store';
import { isEmpty } from 'lodash';
import TestReport from './test.vue';
import SSReport from '../ssreport/HomePageAcross.vue';

// 全局变量定义区 ==========
let { proxy }: any = getCurrentInstance();
let store = AppStore();

const orgList = store.userInfo.orgList;
// 加载状态
let showLoading = ref(false); //左侧表格加载+上方刷新按钮+右侧表单+右侧详情
let saveLoading = ref(false); //保存
let smartScreenTable = ref(null); //table表格
let smartScreenList: any = reactive([]); //table列表数据
let machineVsFunList: any = reactive([]); //table列表数据
let functionDataList: any = reactive([]); //table列表数据
let currentUser = reactive({}); //当前智能屏
let smartScreenForm = reactive({
  id: '',
  smartCode: '',
  smartName: '',
  status: '',
  smartType: '',
  isEnabled: '1',
  searchValue: '',
  smartAddress: '',
  suid:''
});

let showTestReport = ref(true); //显示测试报告

// 定义当前使用的报告组件
const currentReportComponent = computed(() => {
  return showTestReport.value ? TestReport : SSReport;
});

const currentReportRef = computed(() => {
  return showTestReport.value ? 'testReportRef' : 'ssReportRef';
});

const testReportRef = ref<InstanceType<typeof testReportRef>>(); //基本信息表单标记ref

let sltPurpose: any = ref({});
let functionSearchValue = ref('')

const stateList = ref([
  {
    code: 1,
    value: 1,
    name: '运行中',
    label: '运行中',
    color: 'green'
  },
  {
    code: 2,
    value: 2,
    name: '闲置',
    label: '闲置',
    color: 'orange'
  },
  {
    code: 3,
    value: 3,
    name: '故障',
    label: '故障',
    color: 'red'
  }
])

// 页面加载时更新报告单元/字典
onMounted(() => {
  getSmartScreenList(); //加载报告单元列表
  getMachineTypeList();
});

function getIsStaticStatusDesc(row: any) {
  console.log('row', row)
  if (isEmpty(row) || isEmpty(row.status)) {
    return '';
  }
  for (const item of stateList.value) {
    if (row.status == item.value) {
      return item.name;
    }
  }
}
function getIsStaticTagType(row) {
  if (row.isEnabled == 1) {
    return 'success';
  } else if (row.isEnabled == 0) {
    return 'danger';
  }
}

//查询搜索报告单元列表
function getSmartScreenList() {
  showLoading.value = true;
  smartScreenList.length = 0;
  const url = '/smart/screen/findSmartScreenList';
  let obj = {
    keyWords: smartScreenForm.searchValue
  };
  proxy.$http
    .get(url, { params: obj })
    .then((res: any) => {
      smartScreenList.push(...res.data);
      if (smartScreenList.length > 0) {
        const kn = smartScreenList.find((k) => k.id == sltPurpose.value.id);
        if (isEmpty(kn)) {
          userRowClick({ row: smartScreenList[0] });
        } else {
          userRowClick({ row: kn });
        }
      }
      showLoading.value = false;
    })
    .catch((err: any) => {
      proxy.$alert(err, '提示');
    });
  //showLoading.value = true;
}


const smartTypeList = reactive([]);

//查询
function getMachineTypeList() {
  showLoading.value = true;
  smartTypeList.length = 0;
  const url = '/self/machine/type/findMachineTypeList';
  let obj = {
    keyWords: ''
  };
  proxy.$http
    .get(url, { params: obj })
    .then((res: any) => {
      smartTypeList.push(...res.data);
    })
    .catch((err: any) => {
      proxy.$alert(err, '提示');
    });
  //showLoading.value = true;
}


// 回车查询
function keyupEnter(e: any) {
  if (e.$event.code == 'Enter') {
    getSmartScreenList();
  }
}

// 重置
function resetForm(row: any) {
  if (isEmpty(row)) {
    clearForm();
    return;
  }
  smartScreenForm.id = '';
  smartScreenForm.smartCode = '';
  smartScreenForm.smartName = '';
  smartScreenForm.status = '';
  smartScreenForm.smartType = '';
  smartScreenForm.isEnabled = '1';
}

// 点击当前行// 行点击事件(需要调试)
function userRowClick({ row }: any) {
  if (isEmpty(row)) {
    currentUser = {} as any;
    return;
  }

  (proxy.$refs.smartScreenTable as any).setCurrentRow(row);
  Object.assign(smartScreenForm, row);
  findMachineFunctionList(smartScreenForm.suid);
  // const $formRef = testReportRef.value;
  // testReportRef.value.findBarcodeList(smartScreenForm.smartCode);
  //获取中间数据
  //findBarcodeList(smartScreenForm.smartCode);
}

let mockApiResponse: any = reactive([]); //table列表数据

function findMachineFunctionList(suid: any) {
  mockApiResponse.length = 0;
  const url = '/self/machineFunction/findMachineFunction/' + suid;
  proxy.$http
    .get(url)
    .then((res: any) => {
      mockApiResponse.push(...res.data);
      console.log('mockApiResponse', mockApiResponse);

      if (mockApiResponse.length > 0) {

        showTestReport.value = !(mockApiResponse.length === 1 && mockApiResponse[0].funcCode === '001');
        // 根据当前组件调用相应方法
        proxy.$nextTick(() => {
          if (showTestReport.value && testReportRef.value) {
            testReportRef.value?.initParm(mockApiResponse);
          } else {
            //ssReportRef.value?.someMethod?.(smartCode); // 如果SSReport有需要调用的方法
          }
        });

        // if (mockApiResponse.length == 1 && mockApiResponse[0].funcCode == '001') {
        //   showTestReport.value = false;
        // } else {
        //   testReportRef.value.initParm(mockApiResponse);
        // }
      }else{
        showTestReport.value = false;
      }
    })
    .catch((err: any) => {
      proxy.$alert(err, '提示');
    });
}



// 清空右侧表单
function clearForm() {
  smartScreenForm.id = '';
  smartScreenForm.smartCode = '';
  smartScreenForm.smartName = '';
  smartScreenForm.status = '';
  smartScreenForm.smartType = '';
  smartScreenForm.isEnabled = '1';
}

// 删除数据
function handleDelete() {
  const selectRows = (proxy.$refs.smartScreenTable as any).getCheckboxRecords();

  if (selectRows.length <= 0) {
    VxeMessage('请选择需要删除的数据', VxeNotifyType.warning);
    return;
  }
  const url = '/smart/screen/deleteSmartScreen';
  proxy.$http
    .post(url, selectRows)
    .then((res: any) => {
      getSmartScreenList();
      VxeMessage(res.status.msg, VxeNotifyType.success);
    })
    .catch((err: any) => {
      VxeMessage(err, VxeNotifyType.error);
    });
}

// 获取中间的报告单元信息
// function findBarcodeList(smartCode: string) {
//   machineVsFunList.length = 0;
//   const url = '/self/machineFunction/findMachineFunction/' + smartCode;
//   proxy.$http
//     .get(url)
//     .then((res: any) => {
//       machineVsFunList.push(...res.data);
//     })
//     .catch((err: any) => {
//       proxy.$alert(err, '提示');
//     });
// }

//预览
function openNewTab() {
  // 使用Vue Router
  // const router = useRouter()
  // const routeData = router.resolve({ name: 'target-page' })
  // window.open(routeData.href, '_blank')

  // 或者直接使用URL
  //window.open('http://localhost:8080/', '_blank')

  const data = {
    url: '/invHome',
    orderStatus: '5'
  };
  proxy.$router.push({ path: '/slef/testReport', query: data });

}

</script>

<style lang="scss" scoped>
#smartScreenPreview {
  height: 100%;

  .bodyContent {
    height: calc(100% - 60px);

    :deep(.el-tabs) {
      height: 100%;

      .el-tabs__content {
        height: calc(100% - 39px);
        padding: 0;

        .el-tab-pane {
          height: 100%;
        }
      }
    }

    .area {
      background-color: $base-white;

      // 附加按钮间距
      .button-blue,
      .button-red {
        margin: 5px 0 5px 5px;
      }

      .leftTable {
        height: calc(100% - 39px);

        :deep(.vxe-table--render-wrapper) {
          height: 100%;

          .vxe-table--main-wrapper {
            height: 100%;

            .vxe-table--body-wrapper {
              height: calc(100% - 26px) !important;
            }
          }
        }

        :deep(.vxe-table--render-default) {
          height: calc(100% - 36px) !important;
        }
      }

      // 右侧基本信息表单
      .baseForm {
        .el-row {
          margin-left: 0 !important;
          margin-right: 0 !important;
        }

        .form-footer {
          :deep(.el-form-item__content) {
            margin-left: 120px !important;
          }
        }

        .el-form-item--large {
          margin-bottom: 10px;
        }

        .el-radio {
          margin-right: 20px;
        }
      }

      .msgDiv {
        margin-left: 5px;
        color: rgb(180, 28, 28);
      }

      .leftTable {
        height: calc(100% - 39px);

        // :deep(.vxe-table--render-wrapper) {
        //   height: 100%;

        //   .vxe-table--main-wrapper {
        //     height: 100%;

        //     .vxe-table--body-wrapper {
        //       height: calc(100% - 26px) !important;
        //     }
        //   }
        // }

        // :deep(.vxe-table--render-default) {
        //   height: calc(100% - 36px) !important;
        // }
      }

      .el-tabs--border-card {
        border: none;
        height: 100%;

        :deep(.el-tabs__content) {
          height: calc(100% - 39px - 20px);
          padding: 10px;

          .el-tab-pane {
            height: 100%;
          }
        }
      }

      // tab报告单元仪器

      .rptGroupInstrTable {
        height: calc(100% - 24px - 10px);
      }

      .el-radio {
        margin-right: 10px;
      }
    }
  }
}
</style>
